package com.njtoyo.taxi.admin.service.business.operation_rule.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverRegionServiceArrangement;
import com.njtoyo.taxi.admin.mapper.master.enums.DriverRegionServiceArrangementCategory;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverRegionServiceArrangementMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.GeoDriverRegionMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.InformationServiceFeeMapper;
import com.njtoyo.taxi.admin.rest.presenter.business.operation_rule.InformationServiceFeePresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.operation_rule.InformationServiceFeeUpdateActiveWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.business.operation_rule.InformationServiceFeeWrapper;
import com.njtoyo.taxi.admin.service.business.operation_rule.InformationServiceFeeService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class InformationServiceFeeServiceImpl implements InformationServiceFeeService {

    @Autowired
    private DriverRegionServiceArrangementMapper serviceArrangementMapper;
    @Autowired
    private GeoDriverRegionMapper geoDriverRegionMapper;
    @Autowired
    private InformationServiceFeeMapper informationServiceFeeMapper;
    @Autowired
    private OperationRecordHelper operationRecordHelper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override

    public IPage<InformationServiceFeePresenter> getPage(Integer current, Integer size, String driverRegionName) {
        Page<InformationServiceFeePresenter> page = new Page<>(current, size);
        IPage<InformationServiceFeePresenter> pages = informationServiceFeeMapper.getPages(page, driverRegionName);

        return pages;


    }

    @Override
    public RestResult add(InformationServiceFeeWrapper wrapper) {

        DriverRegionServiceArrangement driverRegionServiceArrangement = serviceArrangementMapper.selectOne(Wrappers.<DriverRegionServiceArrangement>lambdaQuery()
                .eq(DriverRegionServiceArrangement::getDriverRegionId, wrapper.getDriverRegionId())
                .eq(DriverRegionServiceArrangement::getServiceCategory, DriverRegionServiceArrangementCategory.info_service_fee));
        if (ObjectUtil.isNotNull(driverRegionServiceArrangement)) {
            return RestResult.failed("运营区配置已存在,请勿重复添加!");
        }

        InformationServiceFeeWrapper.RealTime.PeakHour.TimeDomain[] period = wrapper.getRealtime().getPeakHour().getPeriod();
        Arrays.asList(period).forEach(timeDomain -> {
            Date startTime = null;
            Date endTime = null;
            if (timeDomain.getStartTime().contains("T")) {
                startTime =DateUtil.offsetHour(DateUtil.parseUTC(timeDomain.getStartTime()),8) ;
            }else{
                startTime = DateUtil.parse(timeDomain.getStartTime());
            }
            if (timeDomain.getEndTime().contains("T")) {
                endTime =DateUtil.offsetHour(DateUtil.parseUTC(timeDomain.getEndTime()),8) ;
            }else{
                endTime = DateUtil.parse(timeDomain.getEndTime());
            }
            timeDomain.setStartTime(DateUtil.format(startTime, "HH:mm"));
            timeDomain.setEndTime(DateUtil.format(endTime, "HH:mm"));
        });
        wrapper.setStartTime(wrapper.getStartTime() + " " + "00:00:00");
        wrapper.setEndTime(wrapper.getEndTime() + " " + "23:59:59");
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(wrapper));
        jsonObject.remove("driverRegionId");
        jsonObject.getJSONObject("realtime").getJSONObject("peakHour").put("period", period);


        DriverRegionServiceArrangement entity = new DriverRegionServiceArrangement();
        entity.setDriverRegionId(wrapper.getDriverRegionId());
        entity.setServiceCategory(DriverRegionServiceArrangementCategory.info_service_fee);
        entity.setDetailSpecification(JSON.toJSONString(jsonObject));
        serviceArrangementMapper.insert(entity);

        //清缓存
        redisTemplate.delete("driver:service:arrangement");
        return RestResult.success();
    }

    @Override
    public RestResult update(AdminUser adminUser, InformationServiceFeeWrapper wrapper) {
        DriverRegionServiceArrangement driverRegionServiceArrangement = serviceArrangementMapper.selectOne(Wrappers.<DriverRegionServiceArrangement>lambdaQuery()
                .eq(DriverRegionServiceArrangement::getDriverRegionId, wrapper.getDriverRegionId())
                .eq(DriverRegionServiceArrangement::getServiceCategory, DriverRegionServiceArrangementCategory.info_service_fee)
                .not(i -> i.eq(DriverRegionServiceArrangement::getId, wrapper.getId())));
        if (ObjectUtil.isNotNull(driverRegionServiceArrangement)) {
            return RestResult.failed("修改失败,运营区已存在");
        }


        InformationServiceFeeWrapper.RealTime.PeakHour.TimeDomain[] period = wrapper.getRealtime().getPeakHour().getPeriod();
        Arrays.asList(period).forEach(timeDomain -> {
            Date startTime = null;
            Date endTime = null;
            if (timeDomain.getStartTime().contains("T")) {
                startTime =DateUtil.offsetHour(DateUtil.parseUTC(timeDomain.getStartTime()),8) ;
            }else{
                startTime = DateUtil.parse(timeDomain.getStartTime());
            }
            if (timeDomain.getEndTime().contains("T")) {
                endTime =DateUtil.offsetHour(DateUtil.parseUTC(timeDomain.getEndTime()),8) ;
            }else{
                endTime = DateUtil.parse(timeDomain.getEndTime());
            }
            timeDomain.setStartTime(DateUtil.format(startTime, "HH:mm"));
            timeDomain.setEndTime(DateUtil.format(endTime, "HH:mm"));
        });
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(wrapper));
        jsonObject.remove("driverRegionId");
        jsonObject.remove("id");
        jsonObject.getJSONObject("realtime").getJSONObject("peakHour").put("period", period);


        DriverRegionServiceArrangement entity = new DriverRegionServiceArrangement();
        entity.setId(wrapper.getId());
        entity.setDriverRegionId(wrapper.getDriverRegionId());
        entity.setDetailSpecification(JSON.toJSONString(jsonObject));
        serviceArrangementMapper.updateById(entity);

        //清缓存
        redisTemplate.delete("driver:service:arrangement");

        operationRecordHelper.addBusinessLog(String.format("用户[%s] 的修改了信息服务费 ",adminUser.getName()));
        return RestResult.success();
    }

    @Override
    public RestResult deleteById(Long id) {
        redisTemplate.delete("driver:service:arrangement");
        serviceArrangementMapper.deleteById(id);
        return RestResult.success();
    }

    @Override
    public RestResult getInfoById(Long id) {
        DriverRegionServiceArrangement driverRegionServiceArrangement = serviceArrangementMapper.selectById(id);
        if (ObjectUtil.isNotNull(driverRegionServiceArrangement)) {
            InformationServiceFeeWrapper info = JSON.parseObject(driverRegionServiceArrangement.getDetailSpecification(), InformationServiceFeeWrapper.class);
            info.setDriverRegionId(driverRegionServiceArrangement.getDriverRegionId());
            info.setId(id);
            InformationServiceFeeWrapper.RealTime.PeakHour.TimeDomain[] periods = info.getRealtime().getPeakHour().getPeriod();
            Arrays.asList(periods).forEach(timeDomain -> {
                LocalTime startTime = LocalTime.parse(timeDomain.getStartTime().replaceAll(" ", ""), DateTimeFormatter.ofPattern("HH:mm"));
                LocalTime endTime = LocalTime.parse(timeDomain.getEndTime().replaceAll(" ", ""), DateTimeFormatter.ofPattern("HH:mm"));
                String formatStart = LocalDateTime.of(LocalDate.now(), startTime).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                String formatEnd = LocalDateTime.of(LocalDate.now(), endTime).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                timeDomain.setStartTime(formatStart);
                timeDomain.setEndTime(formatEnd);
            });
            info.getRealtime().getPeakHour().setPeriod(periods);
            return RestResult.success(info);
        }
        return RestResult.success();
    }

    @Override
    public RestResult updateActive(InformationServiceFeeUpdateActiveWrapper wrapper) {
        DriverRegionServiceArrangement driverRegionServiceArrangement = new DriverRegionServiceArrangement();
        driverRegionServiceArrangement.setId(wrapper.getId());
        driverRegionServiceArrangement.setIsOpen(wrapper.getIsOpen());
        serviceArrangementMapper.updateById(driverRegionServiceArrangement);
        redisTemplate.delete("driver:service:arrangement");
        return RestResult.success();
    }
}
